# -*- coding: utf-8 -*-
import traceback
import sys
from moviepy.audio.io.AudioFileClip import AudioFileClip
from moviepy.config import change_settings
from moviepy.editor import VideoFileClip
from moviepy.editor import concatenate_videoclips
from moviepy.video.VideoClip import TextClip
from moviepy import editor

import configs.configs_service as configs_service

change_settings({"IMAGEMAGICK_BINARY": r"C:\Program Files\ImageMagick-7.1.1-Q16-HDRI\magick.exe"})

def create_video(all_short_video_materials, subtiles_materials, audio_file, output_file, fps=24, desired_size=(1024, 1024)):
    try:
        # 处理字幕
        total_duration = 0
        sub_duration = []
        start_time = 0
        subtiles = []
        # 遍历字幕列表
        for subtiles_material in subtiles_materials:
            duration = subtiles_material['duration']
            if duration is None:
                continue

            # 创建字幕剪辑
            subtile = (TextClip(subtiles_material['subtile'], fontsize=40, font='SimHei', size=(configs_service.get_config('movie_sub_length'), configs_service.get_config('movie_sub_hight')), align='center',
                                color='white')
                       .set_position(('center', 'bottom')).set_duration(duration).set_start(start_time))
            subtiles.append(subtile)

            # 更新起始时间
            start_time += duration
            total_duration += duration

        video_clips = []
        for short_video in all_short_video_materials:
            if short_video is None:
                continue

            video_clip = VideoFileClip(short_video)
            video_clips.append(video_clip)

        audio_clip = AudioFileClip(audio_file)

        video_clip = concatenate_videoclips(video_clips)
        final_video = editor.CompositeVideoClip([video_clip, *subtiles])
        final_video = final_video.set_audio(audio_clip)
        final_video = final_video.set_duration(audio_clip.duration)

        final_video.write_videofile(output_file, codec="libx264", audio_codec="aac", fps=fps)
    except Exception as e:
        print(' create_video_v3异常：' + str(e))
